#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QTime>


void Delay_MSec(unsigned int msec)
{
    QTime _Timer = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < _Timer )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 200);
}

bool RxCheckSum(char* Buf){
    unsigned char checksum = 0;
    for(int i=0;i<((unsigned char)Buf[1]-1);++i){
        checksum ^= (unsigned char)Buf[i];
    }
    checksum = ~checksum;
    if((unsigned char)Buf[(unsigned char)Buf[1]-1] == checksum)
        return true;
    return false;
}

void TxCheckSum(unsigned char* data,unsigned char len){
    unsigned char i;
    unsigned char checksum;
    checksum = 0;
    for(i=0;i<(len-1);i++)
    {
        checksum ^= data[i];
    }
    checksum = ~checksum;
    data[len-1] = checksum;
}

void MainWindow::Read_ICCard_Block(unsigned char block){
    unsigned char data[8]={0x01,0x08,0xa3,0x20,0x01,0x01,0x00,0x00};
    data[4] = block;
    data[5] = 0x01;//状态提示
    TxCheckSum(data,data[1]);
    QByteArray byArr = QByteArray((const char*)data,8);
    serialport.write(byArr);
}

void MainWindow::Write_ICCard_Block(unsigned char block,QByteArray info){
    char* ch;
    ch = info.data();
    unsigned char data[23]={0x01,0x17,0xa4,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
    data[4] = block;//block
    data[5] = 0x01;//状态提示
    for(int a=0;a<16;++a){
        data[a+6] = 0x00;
    }
    for(int a=0;a<info.length();++a){
        data[a+6] = (unsigned char)ch[a];
    }
    TxCheckSum(data,data[1]);
    QByteArray byArr = QByteArray((const char*)data,23);
    serialport.write(byArr);
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowIcon(QIcon("rfid_icon.ico"));
    this->setWindowTitle("图书管理系统");
    CardId.resize(4);
    connect(&serialport,&QSerialPort::readyRead,this,&MainWindow::serialport_readyread);
    //连接数据库//输出可用数据库
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("192.168.4.3");
    db.setPort(3306);
    db.setDatabaseName("db_library");
    db.setUserName("goodboy");
    db.setPassword("1234");
    bool ok = db.open();
    if (!ok){
        QMessageBox::information(this, "提示", "MySQL数据库连接失败");
        qDebug()<<"error open database because"<<db.lastError().text();
    }
    db_result = QSqlQuery(db);
    //查看可用的串口
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
    {
        ui->portNameBox->addItem(info.portName());
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::serialport_readyread()
{
    QByteArray buffer = serialport.readAll();
    char* ch;
    ch = buffer.data();
    //写入数据
    if(buffer.length()==8){
        if((unsigned char)ch[4]==0x00){
            if(((unsigned char)ch[0] == 0x01)&&((unsigned char)ch[2] == 0xa4)){
                Set_Count++;
                if( Set_Mode == BOOK_TYPE && Set_Count == 3 ){
                    Set_Count = 0;
                    ////////////////////////
                    db_result.clear();
                    QString cmd = QString("insert into history_val values('%1',%2,NULL,NULL,NULL)").arg(ui->BookNameTextEdit->text()).arg(ui->BookIdTextEdit->text().toInt());
                    if(db_result.exec(cmd)){
                        qDebug() << "成功写入书籍信息!";
                        ui->ResultText->setText("成功写入书籍信息!");
                        qDebug()<<"插入成功！";
                    }else {
                        qDebug()<<"插入失败！";
                    }
                    ////////////////////////
                }else if( Set_Mode == STU_TYPE && Set_Count == 2 ){
                    qDebug() << "成功写入学生信息!";
                    ui->ResultText->setText("成功写入学生信息!");
                    Set_Count = 0;
                }
            }
        }
    }
    //读取卡号
    if(buffer.length()==12){
        if(RxCheckSum(ch)){
            if((unsigned char)ch[4]==0x00){
                if(((unsigned char)ch[0] == 0x04)&&((unsigned char)ch[1] == 0x0C)&&((unsigned char)ch[2] == 0x02)&&((unsigned char)ch[3] == 0x20)){
                    for(int i=0;i<4;++i){
                        CardId[i] = buffer[i+7];
                    }
                    QString s = CardId.toHex();
                    on_clearButton_clicked();
                    qDebug()<<"成功获取卡号:"<< s.toUpper();
                    ui->CardIdText->setText(s.toUpper());
                    //读取块2,获取卡类型; bit0:1为校园卡，2为图书卡;
                    Read_ICCard_Block(CARDID_BLOCK);
                    query_mode = CARDID_BLOCK;
                }
            }
        }
    }
    //读取数据
    if(buffer.length()==22){
        if((unsigned char)ch[4]==0x00){
            if(((unsigned char)ch[0] == 0x01)&&((unsigned char)ch[2] == 0xa3)){
                QByteArray info;
                info.resize(16);
                for(int i=0;i<16;++i){
                    info[i] = buffer[i+5];
                }
                //判断查询内容
                if(query_mode==CARDID_BLOCK){
                    //判断读取的卡类型
                    if(info[0]=='1'){
                        card_type = STU_TYPE;
                        ui->ResultText->setText("校园卡");
                        Read_ICCard_Block(NAME_BLOCK);
                        query_mode = NAME_BLOCK;
                    }else if(info[0]=='2'){
                        card_type = BOOK_TYPE;
                        ui->ResultText->setText("图书卡");
                        Read_ICCard_Block(BOOKINFO_BLOCK);
                        query_mode = BOOKINFO_BLOCK;
                    }else{
                        card_type = 0;
                        ui->ResultText->setText("无效卡");
                    }
                }else if(query_mode==NAME_BLOCK){
                    //读取校园卡的姓名
                    Name = info;
                    qDebug() << "成功读取姓名:" << Name;
                    ui->NameTextEdit->setText(Name);
                    Read_ICCard_Block(STUID_BLOCK);
                    query_mode = STUID_BLOCK;
                }else if(query_mode==STUID_BLOCK){
                    //读取校园卡的学号
                    StuId = info;
                    qDebug() << "成功读取学号:" << StuId;
                    ui->StuIdTextEdit->setText(StuId);
                }else if(query_mode==BOOKINFO_BLOCK){
                    //读取图书卡的信息
                    BookInfo = info;
                    qDebug() << "成功读取图书卡信息:" << BookInfo;
                    int i=0;
                    for(int a=0;BookInfo[i]!='|'&&i<BookInfo.length();++i){
                           BookId[a++]=BookInfo[i];
                    }
                    i++;
                    for(int a=0;BookInfo[i]!='|'&&i<BookInfo.length();++i){
                           BookName[a++]=BookInfo[i];
                    }
                    qDebug() << "成功读取图书卡ID:" << BookId;
                    qDebug() << "成功读取图书卡书籍名称:" << BookName;
                    ui->BookIdTextEdit->setText(BookId);
                    ui->BookNameTextEdit->setText(BookName);
                    Read_ICCard_Block(BOOKPOS_BLOCK);
                    query_mode = BOOKPOS_BLOCK;
                }else if(query_mode==BOOKPOS_BLOCK){
                    //读取图书卡的存储位置
                    BookPos = info;
                    qDebug() << "成功读取图书卡存储位置:" << BookPos;
                    ui->BookPosTextEdit->setText(BookPos);
                }
            }
        }
    }
}

void MainWindow::on_searchButton_clicked()
{
    ui->portNameBox->clear();
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
    {
        ui->portNameBox->addItem(info.portName());
    }
}

void MainWindow::on_openButton_clicked()
{
    if(ui->openButton->text()==QString("打开串口"))
    {
        serialport.setPortName(ui->portNameBox->currentText());
        serialport.setBaudRate(QSerialPort::Baud9600);
        serialport.setDataBits(QSerialPort::Data8);
        serialport.setParity(QSerialPort::NoParity);
        serialport.setStopBits(QSerialPort::OneStop);
        serialport.setFlowControl(QSerialPort::NoFlowControl);
        if(!serialport.open(QIODevice::ReadWrite))
        {
            QMessageBox::about(NULL,"提示","无法打开串口！");
            return ;
        }
        ui->portNameBox->setEnabled(false);
        ui->openButton->setText(QString("关闭串口"));
        ui->writestuButton->setEnabled(true);
    }
    else
    {
        serialport.close();
        ui->portNameBox->setEnabled(true);
        ui->openButton->setText("打开串口");
        ui->writestuButton->setEnabled(false);
    }
}

void MainWindow::on_clearButton_clicked()
{
    ui->CardIdText->clear();
    ui->NameTextEdit->clear();
    ui->StuIdTextEdit->clear();
    ui->BookIdTextEdit->clear();
    ui->BookNameTextEdit->clear();
    ui->BookPosTextEdit->clear();
}

void MainWindow::on_writestuButton_clicked()
{
    Set_Count = 0;
    Set_Mode = STU_TYPE;
    QByteArray data;
    data.resize(16);
    QString Name = ui->NameTextEdit->text();
    QString StuId = ui->StuIdTextEdit->text();
    //设置块1为“1” 表示为校园卡
    Write_ICCard_Block(CARDID_BLOCK,"1");
    Delay_MSec(1000);
    //写入校园卡姓名信息
    data = Name.toUtf8();
    Write_ICCard_Block(NAME_BLOCK,data);
    Delay_MSec(1000);
    //写入校园卡学号信息
    data = StuId.toUtf8();
    Write_ICCard_Block(STUID_BLOCK,data);
}

void MainWindow::on_writebookButton_clicked()
{
    Set_Count = 0;
    Set_Mode = BOOK_TYPE;
    QByteArray data;
    data.resize(16);
    QString BookId = ui->BookIdTextEdit->text();
    QString BookName = ui->BookNameTextEdit->text();
    QString BookPos = ui->BookPosTextEdit->text();
    //设置块1为“2” 表示为图书卡
    Write_ICCard_Block(CARDID_BLOCK,"2");
    Delay_MSec(1000);
    //写入图书卡名称及ID
    data = BookId.toUtf8()+"|"+BookName.toUtf8()+"|";
    Write_ICCard_Block(BOOKINFO_BLOCK,data);
    Delay_MSec(1000);
    //写入图书卡位置信息
    data = BookPos.toUtf8();
    Write_ICCard_Block(BOOKPOS_BLOCK,data);
}
